package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;


    @Transactional
    @Override
    public void addDish(DishDto dto) {
        //先把菜品中的信息进行保存
        this.save(dto);
        //保存口味信息
        List<DishFlavor> flavors = dto.getFlavors();
        //遍历口味信息，给其赋值id。因为菜品保存过之后才会生成id，所以要写在后面
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void updateByDishId(DishDto dto) {
        this.updateById(dto);

        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id",dto.getId());
        dishFlavorService.remove(queryWrapper);
        List<DishFlavor> flavors = dto.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dto.getId()));
        dishFlavorService.saveBatch(flavors);
    }
}
